package com.fr.plugin.utils;

import com.fr.json.JSONObject;
import com.fr.stable.CodeUtils;
import com.fr.third.org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.util.UUID;

public class Utils {

    /**
     * 判断字符串是否为空
     * @param str
     * @return  true 空字符串  false 非空字符串
     */
    public static boolean isNullStr(String str){
        return !(str != null && !str.isEmpty() && !"null".equals(str));
    }

    /**
     * 判断字符串是否非空
     * @param str
     * @return
     */
    public static boolean isNotNullStr(String str){
        return !isNullStr(str);
    }

    /**
     * MD5加密
     * @param str
     * @return
     */
    public static String getMd5Str(String str)
    {
        return DigestUtils.md5Hex(str);
    }


    /**
     * 获取完整的访问路径
     */
    public static String getAllUrl(HttpServletRequest req, String queryStr){
        String url = req.getRequestURL().toString();

        if(isNullStr(queryStr)){
            return url;
        }

        return url+"?"+queryStr;
    }

	/**
     * 帆软shaEncode加密
     */

	public static String shaEncode(String str){
		return CodeUtils.sha256Encode(str);
	}

    /**
     * 获取uuid
     */
    public static String uuid(){
        return UUID.randomUUID().toString();
    }

    public static String replaceNullStr(String str,String replace){
        if(isNullStr(str)){
            return replace;
        }

        return str;
    }

    public static JSONObject getRequestBody(HttpServletRequestWrapper req){
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null)
                sb.append(line);
        } catch (Exception e) {
            FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage());
        }
        //将空格和换行符替换掉避免使用反序列化工具解析对象时失败
        String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n","");

        JSONObject json = new JSONObject(jsonString);

        return json;
    }

}
